# coding: utf8

"""CMS administration panel"""

def user():
    return dict(form=auth())

@auth.requires_login()
def index():
    """List all the documents to be displayed"""
    articles = db().select(db.article.ALL, orderby=~db.article.date)
    response.title = 'Articles list'
    return dict(articles=articles)

@auth.requires_login()
def show():
    """Display an existing article"""
    article = db.article(request.args(0)) or redirect(URL('index'))
    response.title = article.title
    return dict(article=article)
    
@auth.requires_login()
def create():
    """Create a new article"""
    response.title = 'Add article'
    form = crud.create(db.article, next=URL('index'))
    return dict(form=form)

@auth.requires_login()
def edit():
    """Edit an existing article"""
    article = db.article(request.args(0)) or redirect(URL('index'))
    response.title = 'Edit article - %s' % article.title
    form = crud.update(db.article, article, next=URL('show', args=request.args))
    return dict(form=form)
    
@auth.requires_login()
def delete():
    """Delete an existing article"""
    deleted_article = db.article(request.args(0)) or redirect(URL('index'))
    response.title = 'Delete article - %s' % deleted_article.title
    db(db.article.id==request.args(0)).delete()
    return dict(article=deleted_article)
    
@auth.requires_login()
def search():
    """Search an existing article"""
    form = FORM(INPUT(_id='keyword'), _name='keyword', _onkeyup="ajax('bg_find', ['keyword'], 'target');")
    return dict(form=form, target_div=DIV(_id='target'))
    
def bg_find():
    """An ajax callback that returns a <ul> of links to existing articles"""
    pattern = '%' + request.vars.keywords.lower() + '%'
    articles = db(db.article.title.lower().like(pattern)).select(orderby=db.article.title)
    items = [A(article.title, _href=URL('show', args=article.id)) for article in articles]
    return UL(*items).xml()
